<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="机柜名称" prop="cabinetName">
            <el-input
              v-model="baTable.form.items!.cabinetName"
              placeholder="请输入机柜名称"
            />
          </el-form-item>
          <el-form-item label="机柜类型" prop="cabinetType">
            <el-select
              v-model="baTable.form.items!.cabinetType"
              placeholder="请选择机柜类型"
            >
              <el-option
                v-for="item in cabinet.type"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue - 0"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机柜编号" prop="cabinetCode">
            <el-input
              v-model="baTable.form.items!.cabinetCode"
              placeholder="请输入机柜编号"
            />
          </el-form-item>
          <el-form-item label="机柜型号" prop="cabinetModel">
            <el-input
              v-model="baTable.form.items!.cabinetModel"
              placeholder="请输入机柜型号"
            />
          </el-form-item>
          <el-form-item label="机柜规格" prop="cabinetSpecs">
            <el-input
              v-model="baTable.form.items!.cabinetSpecs"
              placeholder="请输入机柜规格"
            />
          </el-form-item>
          <el-form-item label="机柜尺寸" prop="cabinetSize">
            <el-input
              v-model="baTable.form.items!.cabinetSize"
              placeholder="请输入机柜尺寸"
            />
          </el-form-item>
          <el-form-item label="节能率" prop="savingrate">
            <el-input-number
              v-model="baTable.form.items!.savingrate"
              :precision="2"
              :step="1"
            />
          </el-form-item>
          <el-form-item label="覆盖人数" prop="peoplecovered">
            <el-input-number
              v-model="baTable.form.items!.peoplecovered"
              :step="1"
            />
          </el-form-item>
          <el-form-item label="站点" prop="siteId">
            <el-tree-select
              v-model="baTable.form.items!.siteId"
              :data="state.siteOptions"
              node-key="siteId"
              check-strictly
              :props="{
                label: 'siteName',
                value: 'siteId',
                children: 'children',
              }"
              :render-after-expand="false"
              @node-click="siteChange"
            />
          </el-form-item>
          <el-form-item label="告警策略" prop="warningName">
            <el-select
              v-model="baTable.form.items!.warningName"
              @clear="onClear"
              value-key="id"
              @change="selectWarning"
            >
              <el-option
                v-for="(item, index) in state.warningOptions"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="应急电话" prop="emergencyPhone">
            <el-input
              v-model="baTable.form.items!.emergencyPhone"
              placeholder="请输入应急电话"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="baTable.form.items!.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { reactive, ref, inject, onMounted, watch, onBeforeUnmount } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import { useUser } from "@/store/backend/SysM/user";
import { getDictData } from "@/utils/common";
import { useConfig } from "@/store/config"; //后台布局相关仓库

type Option = {
  id: number;
  label: string;
  children: Option[];
};

const filterText = ref("");
const treeRefSupplier = ref<InstanceType<typeof ElTree>>();
const user = useUser();
//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const dictionary = inject("dictionary") as any;
const cabinet = inject("cabinet") as any;
const rule = inject("rule") as any;
const site = inject("site") as any;
const dictOperation = inject("dictOperation") as any;
const formRef = ref<InstanceType<typeof ElForm>>();

const defaultProps = {
  children: "children",
  label: "deptName",
  value: "id",
};
const defaultPropsSupplier = {
  children: "children",
  label: "supplierName",
  value: "supplierId",
};

const state: {
  siteOptions: Option[];
  warningOptions: anyObj[];
} = reactive({
  siteOptions: [], //站点列表
  warningOptions: [], //告警策略列表
});
const rules = reactive<FormRules>({
  cabinetName: [
    { required: true, message: "机柜名称不能为空", trigger: "blur" },
  ],
  cabinetType: [
    { required: true, message: "机柜类型不能为空", trigger: "blur" },
  ],
  siteId: [{ required: true, message: "站点不能为空", trigger: "blur" }],
  emergencyPhone: [
    {
      required: true,
      message: "应急电话不能为空",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
    // { type: "string", message: "长度不能超过30位", trigger: "blur", max: 30 },
  ],
});

//获取机柜管理中站点类型为机柜的的字典值
const getDistrictNum = (val: string) => {
  let len = site.type.length;
  for (let i = 0; i < len; ) {
    if (site.type[i].dictLabel === val) {
      return site.type[i].dictValue - 0;
    } else {
      i++;
    }
  }
};

//选择上级地区站点
const siteChange = (val: any, checked: boolean, childChecked: boolean) => {
  baTable.form.items!.siteName = val.siteName;
  console.log("选择上级地区站点", val, baTable.form.items);
};

//编辑表单保留原始机柜名称待查站点
const keepOriginsiteName = () => {
  baTable.form.operate !== "edit"
    ? (cabinet.editsiteName = "")
    : (cabinet.editsiteName = baTable.form.items!.cabinetName);
};
//判断上级站点名称是否进行了修改
const isSameSiteName = () => {
  if (baTable.form.operate === "edit") {
    site
      .getfilterById({ siteId: baTable.form.items!.siteId })
      .then((res: any) => {
        if (baTable.form.items!.siteName !== res.siteName) {
          baTable.form.items!.siteName = res.siteName;
        }
      });
  }
};

//清空告警策略
const onClear = () => {
  baTable.form.items!.warningId = null;
  baTable.form.items!.warningName = "";
};
//选择告警策略
const selectWarning = (val: any) => {
  console.log("选择告警策略", val);
  baTable.form.items!.warningId = val.id;
  baTable.form.items!.warningName = val.name;
};

//获取告警策略列表数据
const getWarningList = () => {
  rule
    .getWarningRuleList({ pageSize: 90000 })
    .then((res: any) => {
      state.warningOptions = res.rows;
    })
    .catch((err: any) => {});
};

//获取站点数据列表
const getSites = () => {
  site
    .getAssetSiteList({ siteType: getDistrictNum("地区") })
    .then((res: any) => {
      state.siteOptions = res;
      console.log("state.siteOptions", state.siteOptions);
    });
};

onMounted(() => {
  getSites(); //获取站点数据列表
  getWarningList(); //获取告警策略列表数据
  setTimeout(() => {
    keepOriginsiteName(); //编辑表单保留原始设备名称待查站点
    isSameSiteName(); //判断上级站点名称是否进行了修改
  }, 500);
});

watch(filterText, (val) => {
  treeRefSupplier.value!.filter(val);
});
defineExpose({});

onBeforeUnmount(() => {
  cabinet.editsiteName = "";
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  height: 500px;
  overflow-y: auto;
}

.vertical-menus-scrollbar {
  border: 1px solid #e5e6e7;
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  // background: #fff none;
  border-radius: 4px;
}
</style>
